package cloud.code.serverOne.web.controller;

import cloud.code.baseProject.constant.Constant;
import cloud.code.serverOne.web.dto.UserLoginSessionDto;
import cloud.code.serverOne.web.entity.TUserEntity;
import cloud.code.serverOne.web.service.ApiService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class ApiController {

    @Resource
    private ApiService apiService;

    @RequiresPermissions("ccc")
    @RequestMapping(value = "index", produces = {Constant.ContentTypeJson})
    public UserLoginSessionDto index() {
        UserLoginSessionDto dto = new UserLoginSessionDto();
        dto.setPassword("dfsafsa");
        return dto;
    }

    @RequiresRoles("aaa")
    @RequestMapping(value = "index2", produces = {Constant.ContentTypeJson})
    public String index2() {
        return Constant.noAuth;
    }

    @RequiresRoles("ttt")
    @RequestMapping(value = "index3", produces = {Constant.ContentTypeJson})
    public String index3() {
        return apiService.index();
    }

    @RequiresPermissions("666")
    @RequestMapping(value = "index4", produces = {Constant.ContentTypeJson})
    public String index4() {
        return apiService.index();
    }

    @RequestMapping(value = "login", produces = {Constant.ContentTypeJson})
    public String login(@RequestBody TUserEntity tUserEntity) {
        UsernamePasswordToken token = new UsernamePasswordToken(tUserEntity.getLoginName(), tUserEntity.getPassword());

        Subject subject = SecurityUtils.getSubject();
        try {
            //完成登录
            subject.login(token);
            return subject.getSession().getId().toString();
        } catch (Exception e) {
            return e.getMessage();
        }
    }
}